<template>
    <div class="app">
        <!-- 头部 -->
        <div class="favorites-header">
            <div class="favorites-back">
                <a href="#" class="back-button" @click="goBack">
                    <svg t="1742876602916" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3194" width="20" height="20">
                        <path
                            d="M277.382 553.022c-23.136-22.633-23.113-59.378 0.024-82.035l383.961-421.98c23.16-22.657 60.65-22.68 83.786-0.048 23.112 22.657 23.088 59.378-0.048 82.058l-347.407 381.779 346.713 381.035c23.16 22.681 23.401 59.186 0.576 81.555-22.825 22.368-60.122 22.104-83.258-0.553l-383.052-420.97c-0.382-0.361-0.91-0.457-1.294-0.84z"
                            fill="#1296db" p-id="3195">
                        </path>
                    </svg> 
                </a>
            </div>
            <div class="favorites-title">我的作品</div>
            <el-dropdown v-if="works.length" placement="bottom-end">
                <el-button> 操作 </el-button>
                <template #dropdown trigger="click">
                    <el-dropdown-menu>
                        <el-dropdown-item @click="workPageStatus='check'" :icon="workPageStatus=='check' ? Check : ''">
                            <span style="width: 14px;height: 14;margin-right: 5px;" v-if="workPageStatus!='check'"></span>查看
                        </el-dropdown-item>
                        <el-dropdown-item @click="workPageStatus='edit'" :icon="workPageStatus=='edit' ? Check : ''">
                            <span style="width: 14px;height: 14;margin-right: 5px;" v-if="workPageStatus!='edit'"></span>编辑
                        </el-dropdown-item>
                        <el-dropdown-item @click="workPageStatus='delete'" :icon="workPageStatus=='delete' ? Check : ''">
                            <span style="width: 14px;height: 14;margin-right: 5px;" v-if="workPageStatus!='delete'"></span>删除
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
                </el-dropdown>
            <div v-if="workPageStatus=='delete'" class="favorites-edit" style="margin-left: 10px;" @click="toggleCheck">完成</div>
        </div>

        <!-- 标签页 -->
        <div class="favorites-tabs">
            <div v-for="tab in tabs" :key="tab.id" class="favorites-tab" :class="{ active: activeTab === tab.id }"
                @click="activeTab = tab.id">
                {{ tab.label }}
            </div>
        </div>

        <!-- 内容区域 -->
        <div class="content">
            <!-- 空状态 -->
            <div v-if="!works.length" class="favorites-empty">
                <i class="far fa-bookmark favorites-empty-icon"></i>
                <div class="favorites-empty-text">您还没有创作任何作品</div>
                <div class="favorites-empty-button" @click="goToEditNews">去创作</div>
            </div>

            <!-- 作品列表 -->
            <template v-else>
                <div class="favorites-date">文章</div>
                <div class="favorites-list">
                    <div v-for="(item, index) in works" :key="index" class="favorites-item" @click="workPageStatus!='delete' && goToDetail(item)">
                        <div class="list-item">
                            <!--复选框-->
                            <div v-if="workPageStatus=='delete'" class="favorites-item-checkbox">
                                <input type="checkbox" :disabled="checkedItems.length > 0 && !checkedItems.includes(item.id)" :checked="checkedItems.includes(item.id)" @change="selectAllOne(item)" />
                            </div>
                            <div class="list-item-content">
                                <div class="list-item-title">{{ item.title }}</div>
                                <div class="list-item-subtitle">{{ item.categoryName }} · {{ item.publishTime }}</div>

                                <div style="display: flex;  gap: 10px;">
                                    <el-popover v-if="item.status == 2" placement="bottom" title="退回原因" :width="200" trigger="click" :content="item.rejectReason">
                                        <template #reference>
                                            <el-tag @click.stop="" style="cursor: pointer;" type="danger">{{ getStatusName(item.status) }}</el-tag>
                                        </template>
                                    </el-popover>
                                    <el-tag v-if="item.status == 0" type="primary">{{ getStatusName(item.status) }}</el-tag>
                                    <el-tag v-if="item.status == 1" type="success">{{ getStatusName(item.status) }}</el-tag>

                                    <span class="list-item-subtitle" style="display: flex;justify-content: center;align-items: center;">
                                        <svg t="1745127097025" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4752" width="20" height="20">
                                            <path d="M512 416a96 96 0 1 1-96 96 96 96 0 0 1 96-96m0-64a160 160 0 1 0 160 160 160 160 0 0 0-160-160z" 
                                            fill="#333333" p-id="4753"></path>
                                            <path d="M512 298.88c188.64 0 288 113.92 366.72 213.12C800 611.36 700.64 725.12 512 725.12S224 611.36 145.28 512C224 412.64 323.36 298.88 512 298.88m0-64C264.64 234.88 147.52 406.56 64 512c83.52 105.44 200.64 277.12 448 277.12S876.48 617.44 960 512c-83.52-105.44-200.64-277.12-448-277.12z" 
                                            fill="#333333" p-id="4754"></path>
                                        </svg>
                                        {{ item.viewsNum }}
                                    </span>
                                    <span class="list-item-subtitle" style="display: flex;justify-content: center;align-items: center;">
                                        <svg style="margin-right: 3px;" t="1745127522585" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6841" width="18" height="18">
                                            <path d="M667.786667 117.333333C832.864 117.333333 938.666667 249.706667 938.666667 427.861333c0 138.250667-125.098667 290.506667-371.573334 461.589334a96.768 96.768 0 0 1-110.186666 0C210.432 718.368 85.333333 566.112 85.333333 427.861333 85.333333 249.706667 191.136 117.333333 356.213333 117.333333c59.616 0 100.053333 20.832 155.786667 68.096C567.744 138.176 608.170667 117.333333 667.786667 117.333333z m0 63.146667c-41.44 0-70.261333 15.189333-116.96 55.04-2.165333 1.845333-14.4 12.373333-17.941334 15.381333a32.32 32.32 0 0 1-41.770666 0c-3.541333-3.018667-15.776-13.536-17.941334-15.381333-46.698667-39.850667-75.52-55.04-116.96-55.04C230.186667 180.48 149.333333 281.258667 149.333333 426.698667 149.333333 537.6 262.858667 675.242667 493.632 834.826667a32.352 32.352 0 0 0 36.736 0C761.141333 675.253333 874.666667 537.6 874.666667 426.698667c0-145.44-80.853333-246.218667-206.88-246.218667z" 
                                            fill="#000000" p-id="6842"></path>
                                        </svg>
                                        {{ item.likeNum }}
                                    </span>
                                </div>
                            </div>
                            <img v-if="item.frontCover" :src="item.frontCover" width="80" height="60" style="border-radius: 6px; object-fit: cover;"/>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        <!-- 底部操作栏 -->
        <div v-if="workPageStatus=='delete'" class="favorites-actions">
            <div class="favorites-action-button favorites-action-select-all" @click="selectAll">
                {{ checkedItems.length === works.length ? '取消全选' : '全选' }}
            </div>
            <div class="favorites-action-button favorites-action-delete" @click="deleteItems">
                删除
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onActivated, onDeactivated } from 'vue';
import { ArrowDown, Check, CircleCheck, CirclePlus, CirclePlusFilled, Plus,} from '@element-plus/icons-vue'
import { ElLoading } from 'element-plus'
import api from '@/api';
import { useRouter } from 'vue-router';
import { UserStore } from '@/stores/userInfoStore';
import { NewsStore } from '@/stores/newsInfoStore';
import { TipStore } from '@/stores/tipStore';


const router = useRouter();
const userStoreObject = UserStore();
const newsStoreObject = NewsStore();
const TipStoreObject = TipStore();

const News_queryDTO = ref({
  authorId: null,
  status: null,

  current: 1,
  size: 10,
})
const workPageStatus = ref('check') //['check','edit','delete']
const works = ref([])

const activeTab = ref('all');
const tabs = [
    { id: 'all', label: '全部' },
    { id: 'articles', label: '文章' },
    { id: 'videos', label: '视频' },
];
const NewsStatus = ref([
    { label: '待审核', value: 0 },
    { label: '已发布', value: 1 },
    { label: '被撤回', value: 2 },
])

//#region 公用函数

// 获取状态名称
const getStatusName = (statusId) => {
    if(statusId != null){
        return NewsStatus.value.find(s => s.value == statusId)?.label;
    }else{ return null }
};

//从字符串中提取图片地址
const ExtractImgSrc = (htmlString) => {
    let regex = /<img[^>]*\/>/gi; //截取HTML字符串中的<img>标签的正则表达式
    let srcRegex = /src="([^"]*)"/i; //截取<img>标签中的src属性的正则表达式

    let imgTags = htmlString.match(regex); //所有匹配的<img>标签，因为一个文字里面可能有多张图片
    let srcValues = []; //所有src属性的值

    if (imgTags) {
        imgTags.forEach((tag) => {
            let match = tag.match(srcRegex); // 对每个<img>标签使用srcRegex正则表达式，过滤出src属性值
            if (match) {
                srcValues.push(match[1]); // 如果匹配成功，将src属性值添加到数组中
            }
        });
        return srcValues;
    } else {
        return []; //没有找到<img>标签
    }
}
//从字符串中提取视频地址
const ExtractVideoSrc = (htmlString) => {
    let regex = /<video[^>]*>([\s\S]*?)<\/video>/gi; //截取HTML字符串中的以<video开头，以</video>结尾的标签的正则表达式
    let srcRegex = /src="([^"]*)"/i; //截取<video>标签中的src属性的正则表达式

    let videoTags = htmlString.match(regex); //所有匹配的<video>标签，因为一个文章里面可能有多个视频
    let srcValues = []; //所有src属性的值

    if (videoTags) {
        videoTags.forEach((tag) => {
            let match = tag.match(srcRegex); // 对每个<img>标签使用srcRegex正则表达式，过滤出src属性值
            if (match) {
                srcValues.push(match[1]); // 如果匹配成功，将src属性值添加到数组中
            }
        });
        return srcValues;
    } else {
        return []; //没有找到<video>标签
    }
}
//删除文章的同时把它里面的图片或文件从服务器中删掉
const DeleteFile = async (contentList) => {
    console.log("传进来的contentList为：",contentList)

    //如果传进来的是一个【文章内容】数组，（批量删除文章时会用到）
    if(Array.isArray(contentList)){
        for(let i = 0; i < contentList.length; i++){
            let fullPathList_img = ExtractImgSrc(contentList[i]); //提取出图片地址数组
            let fullPathList_video = ExtractVideoSrc(contentList[i]); //提取出视频地址数组
            let fullPathList = fullPathList_img.concat(fullPathList_video); //合并数组
            console.log("（删除文件）准备发送的数据为：",fullPathList);
            await api.deleteObject(fullPathList).then(res => {
                console.log("（删除文件）后端返回的数据为：",res);
            }).catch(err => {
                console.log("错误原因为：",err)
            })
        }
    }
    else{
        let fullPathList_img = ExtractImgSrc(contentList); //提取出图片地址数组
        let fullPathList_video = ExtractVideoSrc(contentList); //提取出视频地址数组
        let fullPathList = fullPathList_img.concat(fullPathList_video); //合并数组
        
        console.log("（删除文件）准备发送的数据为：",fullPathList);
        await api.deleteObject(fullPathList).then(res => {
            console.log("（删除文件）后端返回的数据为：",res);
        }).catch(err => {
            console.log("错误原因为：",err)
        })
    }

}

//删除(单删)
const DeleteFunc = async(newsInfo) =>{

    const loading = ElLoading.service({
        lock: true,
        text: '等待中',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    try{
        // 删除文章的封面
        await api.deleteObject([newsInfo.frontCover])

        // 删除文章里面的文件
        await DeleteFile(newsInfo.content);

        // 删除文章
        await api.deleteOneNews(newsInfo.id).then(res => {
            loading.close()
            tempNewsInfo2.value = null
            router.go(0) //强制刷新页面
        })
    }catch (err) {
        loading.close()
        TipStoreObject.errorTip();
        console.log(err);
    }

}
//#endregion


const goBack = () => {
    router.push('/Profile');
};

const goToEditNews = () => {
    router.push('/EditNews');
};

const goToDetail = (news) => {
    //查看状态
    if(workPageStatus.value=='check'){
        router.push({
            path: '/NewsDetails',
            query: { 
                NewsId: news.id,
                newsCategoryName: news.categoryName
            }
        });
    }
    //编辑状态
    else if(workPageStatus.value=='edit'){
        newsStoreObject.setNewsInfo(news);
        router.push({path: '/EditNews2',});
    }

};


//#region 关于复选框
const checkedItems = ref([]);
const tempNewsInfo2 = ref({})
//切换为查看状态
const toggleCheck = () => {
    checkedItems.value = [];
    workPageStatus.value = 'check';
};
//单选
const selectAllOne = (item) => {
    tempNewsInfo2.value = item
    const isChecked = checkedItems.value.includes(item.id);
    if (isChecked) {
        checkedItems.value = checkedItems.value.filter((i) => i !== item.id);
    } else {
        checkedItems.value.push(item.id);
    }
};
//全选
const selectAll = () => {
    alert("暂不支持作品多删")
    // if (checkedItems.value.length === works.value.length) {
    //     checkedItems.value = [];
    // } else {
    //     checkedItems.value = works.value.map(item => item.id);
    // }
};

//删除按钮
const deleteItems = () => {
    let res = confirm("删除后不可恢复，确认删除吗？")
    if(!res){
        return
    }
    DeleteFunc(tempNewsInfo2.value)
};
//#endregion


onMounted(async()=>{
    console.log("作品页被挂载了！")
    //查找该用户的作品
    News_queryDTO.value.authorId = userStoreObject.userInfo.id
    await api.getNewsInCondition(News_queryDTO.value).then(res => {
      if(res.data.code == 1){
        works.value = res.data.data.list
      }else{
        console.log('获取作品失败')
      }
    }).catch(err => {
      console.log('获取作品失败',err)
    })
})

//当前组件被用keep-alive缓存了，会有两个新的生命周期函数
onActivated(() => {
    
});
onDeactivated(() => {
   
});


</script>

<style lang="scss" scoped>
.app {
    font-family: Arial, sans-serif;
}

.status-bar {
    display: flex;
    justify-content: space-between;
    padding: 8px;
    background-color: #f2f2f7;
}

.favorites-header {
    padding: 16px;
    background-color: #fff;
    border-bottom: 1px solid #eaeaea;
    display: flex;
    align-items: center;
}

.favorites-title {
    font-size: 18px;
    font-weight: 600;
    flex: 1;
    text-align: center;
}

.favorites-back,
.favorites-edit {
    font-size: 16px;
    color: #007aff;
}

.favorites-tabs {
    display: flex;
    background-color: #fff;
    border-bottom: 1px solid #eaeaea;
}

.favorites-tab {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    font-size: 15px;
    color: #8e8e93;
    position: relative;
}

.favorites-tab.active {
    color: #007aff;
    font-weight: 600;
}

.favorites-tab.active:after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 25%;
    width: 50%;
    height: 3px;
    background-color: #007aff;
    border-radius: 1.5px;
}

.favorites-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 16px;
    text-align: center;
}

.favorites-empty-icon {
    font-size: 60px;
    color: #c7c7cc;
    margin-bottom: 16px;
}

.favorites-empty-text {
    font-size: 16px;
    color: #8e8e93;
    margin-bottom: 24px;
}

.favorites-empty-button {
    background-color: #007aff;
    color: white;
    padding: 12px 24px;
    border-radius: 20px;
    font-weight: 600;
}

.favorites-list {
    display: grid;
    padding: 16px;
    gap: 15px;
}

.favorites-item {
    // position: relative;
    display: block;
    border-bottom: 1px solid #eaeaea;
}

.favorites-item-checkbox {
    // position: absolute;
    // left: -30px;
    // top: 50%;
    // transform: translateY(-50%);
    margin-right: 5px;
}

.favorites-item-checkbox input[type='checkbox'] {
    width: 20px;
    height: 20px;
}

.favorites-actions {
    display: flex;
    justify-content: space-between;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #eaeaea;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
}

.favorites-action-button {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    border-radius: 8px;
    font-weight: 600;
}

.favorites-action-select-all {
    background-color: #f2f2f7;
    color: #007aff;
    margin-right: 8px;
}

.favorites-action-delete {
    background-color: #ff3b30;
    color: white;
}

.favorites-date {
    padding: 8px 16px;
    font-size: 14px;
    color: #8e8e93;
    background-color: #f2f2f7;
    position: sticky;
    top: 0;
    z-index: 1;
}

.list-item {
    display: flex;
    align-items: center;
}

.list-item-content {
    flex: 1;
}

.list-item-title {
    font-size: 16px;
    font-weight: 500;
}

.list-item-subtitle {
    font-size: 14px;
    color: #8e8e93;
    margin-bottom: 10px;
}
</style>